<?PHP
session_start();
include_once "ini.php";
$tag = $_POST['tag'];
$id_cam = $_POST['id_cam'];
dbconnect();
//****INDEXATION
$query = "SELECT * FROM indexation WHERE keyword = '".$tag."';";
$result = mysql_query($query);
if (!$result)
{
    echo "SQL error : ", $query;
    exit ;
}
else
{
    $tab = mysql_fetch_assoc($result);
    if ($tab['keyword'] != "")
    {
        $id_mot = $tab['id_mot'];
        $occurence = $tab['occurence']+1;
        $sql = "UPDATE `indexation` SET `occurence` = '".$occurence."' WHERE `indexation`.`id_mot` = '".$tab['id_mot']."' LIMIT 1 ;";
        $requete = mysql_query($sql);
        if (!$requete)
        {
            echo "SQL error : ", $sql;
            exit ;
        }
        else
        {
            echo "save update indexation done \r\n";

        }
    }
    else
    {
        $sql = "INSERT into indexation VALUES ('', '".$tag."', '1');";
        $requete = mysql_query($sql);
        if (!$requete)
        {
            echo "SQL error : ", $sql;
            exit ;
        }
        else
        {
            echo "save indexation done \r\n";

        }
    }

}
//****TAG
if ($id_mot != "")
{
    $query = "SELECT * FROM tags WHERE id_mot = '".$id_mot."' AND id_user = '".$id_cam."';";
    $result = mysql_query($query);
    if (!$result)
    {
        echo "SQL error : ", $query;
        exit ;
    }
    else
    {
        $tab = mysql_fetch_assoc($result);
        if ($tab['id_user'] != "") //un mot existe dejà pour ce user
        {
            $occurence = $tab['tag_occurence']+1;
            $sql = "UPDATE `tags` SET `tag_occurence` = '".$occurence."' WHERE `tags`.`id_mot` = '".$id_mot."' AND id_user = '".$id_cam."' LIMIT 1 ;";
            $requete = mysql_query($sql);
            if (!$requete)
            {
                echo "SQL error : ", $sql;
                exit ;
            }
            else
            {
                echo "save update tag done \r\n";

            }
        }
        else
        {
            $sql = "INSERT into tags VALUES ('".$id_cam."', '".$id_mot."', '1');";
            $requete = mysql_query($sql);
            if (!$requete)
            {
                echo "SQL error : ", $sql;
                exit ;
            }
            else
            {
                echo "save tag done \r\n";

            }
        }
    }
}
else{
	$query = "SELECT * FROM indexation WHERE keyword= '".$tag."';";
	$result = mysql_query($query);
	$tabl = mysql_fetch_assoc($result);
	$id_mot = $tabl['id_mot'];
	$sql = "INSERT into tags VALUES ('".$id_cam."', '".$id_mot."', '1');";
            $requete = mysql_query($sql);
            if (!$requete)
            {
                echo "SQL error : ", $sql;
                exit ;
            }
            else
            {
                echo "save tag done \r\n";

            }
}
dbclose();
?>
